package com.myapp.ruyixing.ui;

import java.util.List;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.NearbyStores;
import com.myapp.ruyixing.model.NearbyStores.Store;
import com.myapp.ruyixing.model.RankCategory;
import com.myapp.ruyixing.model.RankCategory.RankSubCategory;
import com.myapp.ruyixing.model.RankCategory.RankTopCategory;
import com.myapp.ruyixing.utils.BitmapLruCache;
import com.myapp.ruyixing.utils.UIUtils;

public class RankActivity extends BaseActivity implements OnClickListener,
		OnItemClickListener {

	private ListView mListView;
	private TextView mEmptyView;

	private View mLoadingView;
	private TextView mTitleView;
	private View mShadowsView;

	private View mFocusedTabView;

	private View mMenuLayout;

	private RankCategory mCategory;

	private String mActiveTopCategory;
	private String mActiveSubCategory;

	private RYHttpResponseHandler mHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			NearbyStores stores = (NearbyStores) o;

			if (stores != null && stores.items != null) {
				MyListAdapter adapter = new MyListAdapter(stores.items);
				mListView.setAdapter(adapter);
			}
			mListView.setEmptyView(mEmptyView);
			mLoadingView.setVisibility(View.GONE);
		}

		@Override
		public void onFailure(Throwable throwable) {
			if (!isFinishing()) {
				Toast.makeText(getApplicationContext(), "加载失败",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	private RYHttpResponseHandler mCategoryHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			RankCategory category = (RankCategory) o;

			if (category != null && category.data != null) {
				mCategory = category;

				requestData();
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			if (!isFinishing()) {
				Toast.makeText(getApplicationContext(), "加载失败",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		setContentView(R.layout.activity_rank);

		initView();

		mActiveTopCategory = "餐厅排行榜";
		mActiveSubCategory = "热门商家";
		mLoadingView.setVisibility(View.VISIBLE);
		RYHttpClient.getRankCategory(this, mCategoryHandler);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_icon:
			finish();
			break;
		case R.id.text_title:
			showMenu();
			break;

		case R.id.hot:
		case R.id.best:
		case R.id.service:
			changeTab(v);
			break;
		case R.id.more:
			showMoreCategory(v);
			break;

		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		if (position >= 0 && position < mListView.getAdapter().getCount()) {
			Store item = (Store) mListView.getAdapter().getItem(position);
			ShopDetailActivity.startShopDetailActivity(this, item.merchant_id);
		}
	}

	public void changeType(String value, String name) {
		mActiveTopCategory = name;
		mTitleView.setText(name);
		hideMenu();

		requestData();
	}

	public void changeSubType(String value, String name) {
		findViewById(R.id.more_menus).setVisibility(View.GONE);
		mShadowsView.setVisibility(View.GONE);

		requestData(value);
	}

	private String getCategoryId() {
		for (RankTopCategory topCategory : mCategory.data) {
			if (mActiveTopCategory.equals(topCategory.name)) {
				for (RankSubCategory subCategory : topCategory.categories) {
					if (mActiveSubCategory.equals(subCategory.name)) {
						return subCategory.id;
					}
				}
			}
		}

		return null;
	}

	private void requestData() {
		String categoryId = getCategoryId();
		if (TextUtils.isEmpty(categoryId)) {
			Toast.makeText(getApplicationContext(), "加载失败", Toast.LENGTH_SHORT)
					.show();
			return;

		}

		requestData(categoryId);
	}

	private void requestData(String categoryId) {
		mLoadingView.setVisibility(View.VISIBLE);
		RYHttpClient.getTopShopList(this, mHandler, categoryId);
	}

	private void changeTab(View v) {
		if (mFocusedTabView == v) {
			return;
		}

		mFocusedTabView.setSelected(false);
		mFocusedTabView = v;
		mFocusedTabView.setSelected(true);
		mActiveSubCategory = ((TextView) mFocusedTabView).getText().toString();

		requestData();
	}

	private void showMoreCategory(View v) {
		if (mFocusedTabView != v) {
			mFocusedTabView.setSelected(false);
			mFocusedTabView = v;
			mFocusedTabView.setSelected(true);
			mActiveSubCategory = ((TextView) mFocusedTabView).getText().toString();
		}

		String categoryId = getCategoryId();
		RankMoreMenuFragment fragment = RankMoreMenuFragment
				.getInstance(categoryId);
		findViewById(R.id.more_menus).setVisibility(View.VISIBLE);
		mShadowsView.setVisibility(View.VISIBLE);
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.more_menus, fragment).commit();
	}

	private void initView() {
		mListView = (ListView) findViewById(android.R.id.list);
		mEmptyView = (TextView) findViewById(android.R.id.empty);
		mLoadingView = findViewById(R.id.loading);
		mTitleView = (TextView) findViewById(R.id.text_title);
		mFocusedTabView = findViewById(R.id.hot);
		mShadowsView = findViewById(R.id.shadows);
		mMenuLayout = findViewById(R.id.menus);

		mFocusedTabView.setSelected(true);
		mListView.setOnItemClickListener(this);

		findViewById(R.id.img_icon).setOnClickListener(this);
		mTitleView.setOnClickListener(this);

		mFocusedTabView.setOnClickListener(this);
		findViewById(R.id.best).setOnClickListener(this);
		findViewById(R.id.service).setOnClickListener(this);
		findViewById(R.id.more).setOnClickListener(this);
	}

	private void showMenu() {
		mMenuLayout.setVisibility(View.VISIBLE);
		mShadowsView.setVisibility(View.VISIBLE);
	}

	private void hideMenu() {
		mMenuLayout.setVisibility(View.GONE);
		mShadowsView.setVisibility(View.GONE);
	}

	private class ViewHolder {
		TextView mTitleView;
		TextView mPriceView;
		NetworkImageView mShopImage;
		TextView mDistanceView;
		ImageView mScoreView;
		TextView mLabelsView;
		View mCardIndicatorView;
		View mTicketIndicatorView;
		View mBenifitIndicatorView;
	}

	private class MyListAdapter extends ArrayAdapter<Store> {

		private RequestQueue mQueue;
		private ImageLoader mImageLoader;

		public MyListAdapter(List<Store> list) {
			super(RankActivity.this, -1, list);
			mQueue = Volley.newRequestQueue(RankActivity.this);
			mImageLoader = new ImageLoader(mQueue, new BitmapLruCache());
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(RankActivity.this).inflate(
						R.layout.shop_list_item, parent, false);

				ViewHolder holder = new ViewHolder();
				holder.mTitleView = (TextView) convertView
						.findViewById(R.id.text_shop_name);
				holder.mPriceView = (TextView) convertView
						.findViewById(R.id.text_average_cost);
				holder.mShopImage = (NetworkImageView) convertView
						.findViewById(R.id.image_shop);
				holder.mDistanceView = (TextView) convertView
						.findViewById(R.id.text_distance);
				holder.mScoreView = (ImageView) convertView
						.findViewById(R.id.score);
				holder.mLabelsView = (TextView) convertView
						.findViewById(R.id.text_keywords);
				holder.mCardIndicatorView = convertView
						.findViewById(R.id.img_ka);
				holder.mTicketIndicatorView = convertView
						.findViewById(R.id.img_quan);
				holder.mBenifitIndicatorView = convertView
						.findViewById(R.id.img_hui);

				convertView.setTag(holder);
			}

			ViewHolder mHolder = (ViewHolder) convertView.getTag();

			NearbyStores.Store item = getItem(position);

			mHolder.mTitleView.setText(item.merchant_name);
			int price = 0;
			try {
				price = Integer.parseInt(item.price);
			} catch (Exception e) {
			}
			mHolder.mPriceView.setText(getString(R.string.store_price, ""
					+ price));
			mHolder.mLabelsView.setText(item.keywords);
			mHolder.mScoreView.setImageLevel(item.score);
			long sDistance = item.distance;
			String picurl = item.picurl;

			if (sDistance >= 0) {
				String distance = "";
				if (sDistance >= 1000) {
					if (sDistance >= 1000000) {
						distance = "999+km";
					} else {
						distance = String.format("%.1fkm",
								((double) sDistance) / 1000);
					}
				} else {
					distance = sDistance + "m";
				}
				mHolder.mDistanceView.setText(distance);
			}

			if (!TextUtils.isEmpty(picurl)) {
				mHolder.mShopImage.setImageUrl(picurl, mImageLoader);
			}

			UIUtils.setViewVisibility(mHolder.mCardIndicatorView,
					"1".equals(item.card));
			UIUtils.setViewVisibility(mHolder.mTicketIndicatorView,
					"1".equals(item.ticket));
			UIUtils.setViewVisibility(mHolder.mBenifitIndicatorView,
					"1".equals(item.benefit));

			return convertView;

		}
	}
}
